<template>
  <div class="w-1/1 h-1/1" :class="{ 'data-binding-hidden': !isVisible }">
    <svg-render
      v-if="item_json.type === 'svg' && item_json.symbol"
      draggable="false"
      :symbol-id="item_json.symbol.symbol_id"
      :symbol-str="item_json.symbol.symbol_str"
      :width="item_json.symbol.width"
      :height="item_json.symbol.height"
      :props="item_json.props"
    ></svg-render>
    <group-render
      v-else-if="item_json.type === 'group'"
      :item-json="item_json"
      :grid="renderItemProps.grid"
      :canvas-cfg="renderItemProps.canvasCfg"
      :canvas-dom="renderItemProps.canvasDom"
    ></group-render>
    <component
      v-else-if="item_json.type === 'vue'"
      draggable="false"
      :is="getCorrectTag(item_json)"
      v-bind="getComponentProps(item_json)"
      @update:modelValue="(val: any) => onUpdateModelValue(item_json.props, val)"
    ></component>
    <server-svg-render
      v-else-if="item_json.type === 'server-svg'"
      draggable="false"
      :src="item_json.thumbnail || ''"
      :props="item_json.props"
    ></server-svg-render>
    <img
      v-else-if="item_json.type === 'img' || (item_json.type === 'svg' && !item_json.symbol)"
      draggable="false"
      class="w-1/1 h-1/1"
      :src="item_json.thumbnail"
    />
    <custom-svg-render v-else-if="item_json.type === 'custom-svg'">
      <component
        :is="item_json.tag"
        v-bind="prosToVBind(item_json.props)"
        :id="item_json.id"
      ></component>
    </custom-svg-render>
    <line-render
      v-else-if="item_json.type === 'sys-line'"
      v-model:item-json="item_json"
      :canvas-cfg="renderItemProps.canvasCfg"
      :grid="renderItemProps.grid"
      :canvas-dom="renderItemProps.canvasDom"
      :done-json="renderItemProps.doneJson"
      :lock-state="renderItemProps.lockState"
      :mode="renderItemProps.lineAppendEnable ? 'line-edit' : 'normal'"
      @set-intention="(val) => emits('setIntention', val)"
      @line-mouse-up="emits('lineMouseUp')"
    ></line-render>
  </div>
</template>
<script setup lang="ts">
import type {
  IDoneJson,
  IGlobalStoreCanvasCfg,
  IGlobalStoreGridCfg,
  ILeftAsideConfigItemPublicProps
} from '../../store/types';
import SvgRender from '@/components/mt-edit/components/svg-render/index.vue';
import ServerSvgRender from '@/components/mt-edit/components/server-svg-render/index.vue';
import GroupRender from '@/components/mt-edit/components/group-render/index.vue';
import { prosToVBind } from '@/components/mt-edit/utils';
import LineRender from '@/components/mt-edit/components/line-render/index.vue';
import CustomSvgRender from '@/components/mt-edit/components/custom-svg-render/index.vue';
import { computed, onMounted, onBeforeUpdate, onUpdated, onUnmounted } from 'vue';
import { startComponentRender, endComponentRender } from '@/utils/performance-monitor';
type RenderItemProps = {
  itemJson: IDoneJson;
  canvasCfg: IGlobalStoreCanvasCfg;
  grid: IGlobalStoreGridCfg;
  canvasDom: HTMLElement | null;
  doneJson?: IDoneJson[];
  lockState: boolean;
  lineAppendEnable?: boolean;
  previewMode?: boolean;
};
const renderItemProps = withDefaults(defineProps<RenderItemProps>(), {
  doneJson: () => [],
  lineAppendEnable: false,
  previewMode: false
});
const emits = defineEmits(['update:itemJson', 'setIntention', 'lineMouseUp']);
const item_json = computed({
  get: () => renderItemProps.itemJson,
  set: (value) => {
    emits('update:itemJson', value);
  }
});
const onUpdateModelValue = (props: ILeftAsideConfigItemPublicProps, value: any) => {
  if (props.modelValue) {
    emits('update:itemJson', {
      ...item_json.value,
      props: {
        ...item_json.value.props,
        modelValue: {
          ...item_json.value.props.modelValue,
          val: value
        }
      }
    });
  }
};

// 修复组件tag的函数
const getCorrectTag = (itemJson: IDoneJson) => {
  // 如果tag等于id，说明tag被错误设置了，需要修复
  if (itemJson.tag === itemJson.id) {
    // 根据id映射到正确的tag
    const idToTagMap: Record<string, string> = {
      'echart-gauge-dashboard': 'gauge-dashboard-vue',
      'echart-gauge-simple': 'gauge-simple-vue',
      'echart-gauge-ability': 'gauge-ability-vue',
      'echart-gauge-completion': 'gauge-completion-vue',
      'echart-gauge-tower': 'gauge-tower-vue',
      'echart-gauge-cpu': 'gauge-cpu-vue',
      'echart-gauge-clean': 'gauge-clean-vue',
      'echart-gauge-progress': 'gauge-progress-vue',
      'echart-gauge-thick': 'gauge-thick-vue',
      'echart-gauge-colorful': 'gauge-colorful-vue',
      'echart-gauge-temperature': 'gauge-temperature-vue',
      'echart-gauge-double': 'gauge-double-vue',
      'echart-liquid-fill': 'liquid-fill-vue',
      'echart-universal': 'echart-universal-vue'
    };

    const correctTag = idToTagMap[itemJson.id];
    if (correctTag) {
      return correctTag;
    }
  }

  // 特殊处理：如果id以特定前缀开头，强制使用正确的tag
  if (itemJson.id.startsWith('echart-gauge-dashboard')) {
    return 'gauge-dashboard-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-simple')) {
    return 'gauge-simple-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-ability')) {
    return 'gauge-ability-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-completion')) {
    return 'gauge-completion-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-tower')) {
    return 'gauge-tower-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-cpu')) {
    return 'gauge-cpu-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-clean')) {
    return 'gauge-clean-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-progress')) {
    return 'gauge-progress-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-thick')) {
    return 'gauge-thick-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-colorful')) {
    return 'gauge-colorful-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-temperature')) {
    return 'gauge-temperature-vue';
  }

  if (itemJson.id.startsWith('echart-gauge-double')) {
    return 'gauge-double-vue';
  }

  if (itemJson.id.startsWith('echart-liquid-fill')) {
    return 'liquid-fill-vue';
  }

  return itemJson.tag;
};

// 获取组件属性，包含数据绑定配置
const getComponentProps = (itemJson: IDoneJson) => {
  const baseProps = prosToVBind(itemJson.props);

  // 如果组件有数据绑定配置，添加到props中
  if (itemJson.data_binding) {
    baseProps.dataBinding = itemJson.data_binding;
  }

  return baseProps;
};

// 计算最终的显示状态
const isVisible = computed(() => {
  // 在编辑模式下，组件应该始终可见以支持拖拽和编辑
  if (!renderItemProps.previewMode) {
    return true;
  }
  // 在预览模式下，使用组件的hide属性控制可见性
  return !item_json.value.hide;
});

// 性能监控
const componentId = computed(() => `render-item-${item_json.value.id}`);
const componentType = computed(() => `RenderItem(${item_json.value.type})`);

onMounted(() => {
  startComponentRender(componentId.value, componentType.value);
});

onBeforeUpdate(() => {
  startComponentRender(componentId.value, componentType.value);
});

onUpdated(() => {
  endComponentRender(componentId.value, componentType.value);
});
</script>
<style scoped>
.data-binding-hidden {
  display: none !important;
}
</style>
